#include "function/function.h"
#include <QDebug>

//#include "mainwindow.h"

#include <QCoreApplication>
#include <QDir>
#include <QFile>


QString IpPort;//服务器ip
QString IpPort_2;//服务器ip

//加载完整地址
QString URLName(QString name)
{
//    return QString("%1%2").arg(IpPort, name);
    return QString("%1/api%2").arg(IpPort_2, name);
}

QString URLName_2(QString name)
{
    QString url = QString("%1/api/management-client/%2").arg(IpPort_2, name);
//    qDebug()<<__LINE__<<url;
    return url;
}

void configuration(QString path)
{
    path = searchConfigFile(path);
    //创建QFile
    QFile myfile(path);
    //打开文件
    bool ret=myfile.open(QIODevice::ReadOnly);
    if(!ret)
    {
        qDebug()<<__LINE__<<"打开配置文件失败"<<"path="<<path;
        return;
    }
    while(!myfile.atEnd())
    {
        //读取一行数据
        QByteArray array=myfile.readLine();
        QString buf;
//        buf = array.replace(" ","");
        buf = array.replace("\r","");
        buf = array.replace("\n","");

        QStringList mylist = buf.split("##");//如果有注释则解析掉注释部分
        QStringList list = mylist.at(0).split("=");
        if(list.size() < 2) continue;


        if(list.at(0) == "IpPort")
        {
            IpPort = list.at(1);
            qDebug()<<__LINE__<<"服务器ip端口号"<<"IpPort="<<IpPort;
        }
        else if(list.at(0) == "IpPort_2")
        {
            IpPort_2 = list.at(1);
            qDebug()<<__LINE__<<"服务器ip端口号"<<"IpPort_2="<<IpPort_2;
        }
    }

    myfile.close();
}

QString searchConfigFile(QString ConfigFileName)
{
//    char *buffer;
//    buffer = getcwd(NULL, 0);

    QString binDir=QCoreApplication::applicationDirPath();
    QString appName=QCoreApplication::applicationName();
//    QByteArray ary=
//    QString binDir=QString::fromUtf8(buffer);
//    qDebug()<<binDir<<"                "<<appName<<buffer;
    QFile file;
    file.setFileName(binDir+"/"+ConfigFileName);
    if (!file.exists()) {
        file.setFileName(binDir+"/etc/"+ConfigFileName);
        if (!file.exists()) {
            file.setFileName(binDir+"/../etc/"+ConfigFileName);
            if (!file.exists()) {
                file.setFileName(binDir+"/../"+appName+"/etc/"+ConfigFileName);
                if (!file.exists()) {
                    file.setFileName(binDir+"/../../"+appName+"/etc/"+ConfigFileName);
                    if (!file.exists()) {
                        file.setFileName(binDir+"/../../../../../"+appName+"/etc/"+ConfigFileName);
                        if (!file.exists()) {
                            file.setFileName(QDir::rootPath()+"etc/"+ConfigFileName);
                        }
                    }
                }
            }
        }
    }
    if (file.exists()) {
        QString configFileName=QDir(file.fileName()).canonicalPath();	//将相对路径换成绝对路径
        qDebug("using config file %s", qPrintable(configFileName));
        return configFileName;
    }
    else {
        qFatal("config file not found");	//找不到该文件，则应用程序将输出一条错误消息，并中止程序
    }

}
